package org.summer.generator.channel;

import org.summer.generator.log.Logger;
import org.summer.generator.log.LoggerManager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * 高级文件写入通道,使用缓冲区
 *
 * @author gvp9132
 * @date 2024/10/26 20:08
 * @since 1.0.0
 */
public class AdvancedFileWriterChannel implements FileWriterChannel {
    private static final Logger log = LoggerManager.getLogger(AdvancedFileWriterChannel.class);
    private final ByteBuffer buffer = ByteBuffer.allocate(1024);
    private final FileOutputStream os;
    private final FileChannel channel;

    public AdvancedFileWriterChannel(File file) throws FileNotFoundException {
        this.os = new FileOutputStream(file);
        this.channel = os.getChannel();
    }

    @Override
    public void writer(String content) {
        byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
        if (bytes.length >= 2048 ){
            log.error("当前需要写入文件内容超过缓冲区大小,请调整缓冲区大小");
        }
        if (buffer.remaining() < bytes.length) {
            log.debug("文件写入通道缓存区已满,将缓冲区内容写入文件,正常执行写入");
            writerHandler();
        }
        buffer.put(bytes);
    }

    @Override
    public void beforeClose() {
        log.debug("文件写入通道关闭通道前执行写入,清空缓冲区写入");
        if (buffer.hasRemaining()) {
            writerHandler();
        }
    }

    private void writerHandler() {
        try {
            buffer.flip();
            channel.write(buffer);
            buffer.clear();
        } catch (IOException e) {
            log.error("通道向文件写入内容时出现错误", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void close() throws Exception {
        channel.close();
        os.close();
    }
}
